<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" :placeholder="$t('system.menu.name')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('system.search') }}
      </el-button>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('system.menu.createMenu') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('system.export') }}
      </el-button>
      <el-checkbox v-model="showCreator" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        {{ $t('system.menu.creator') }}
      </el-checkbox>
    </div>

    <el-table
      :key="tableKey"
      ref="multipleTable"
      v-loading="listLoading"
      :data="menuList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column :label="$t('system.menu.name')" min-width="170px">
        <template slot-scope="{row}">
          <span>{{ "&nbsp;&nbsp;&nbsp;".repeat(row.level) }}|{{ " _ _ ".repeat(row.level+1) }}{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('system.menu.parentName')" min-width="110px">
        <template slot-scope="{row}">
          <span>{{ row.parentName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('system.menu.orderNum')" min-width="40px">
        <template slot-scope="{row}">
          <span>{{ row.orderNum }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('system.menu.level')" min-width="40px">
        <template slot-scope="{row}">
          <span>{{ row.level }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('system.menu.remark')" min-width="110px">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showCreator" :label="$t('system.menu.creator')" width="110px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.creator }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('system.menu.createTime')" prop="createTime" sortable="custom" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('system.menu.updateTime')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('system.actions')" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope)">
            {{ $t('system.edit') }}
          </el-button>
          <el-button v-if="scope.row.deleteFlag!=='1'" size="mini" type="danger" @click="handleDelete(scope)">
            {{ $t('system.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="footer-container">
      <el-row>
        <el-col :span="12"><div class="footer-left-container"><el-button @click="reverseSelect()">反选</el-button><el-button @click="toggleSelection()">取消选择</el-button></div> </el-col>
        <el-col :span="12"> <pagination v-show="total>0" :hide-on-single-page="true" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getMenu" /> </el-col>
      </el-row>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-dialog
        width="30%"
        title="选择父级部门树"
        :visible.sync="dialogInnerVisible"
        append-to-body
      >
        <el-tree
          ref="menuTree"
          :data="treeMenuData"
          show-checkbox
          default-expand-all
          node-key="menuId"
          :check-strictly="true"
          highlight-current
          :default-checked-keys="menuTreeDefaultKeys"
          :props="defaultProps"
          @check-change="menuTreeCheckChange"
          @node-click="menuTreeClick"
        />
        <div slot="footer" class="dialog-footer">
          <el-button v-waves @click="dialogInnerVisible = false">
            {{ $t('system.cancel') }}
          </el-button>
          <el-button v-waves type="primary" @click="dialogInnerVisible = false">
            {{ $t('system.confirm') }}
          </el-button>
        </div>
      </el-dialog>
      <el-form ref="dataForm" :rules="rules" :model="menu" label-position="left" label-width="100px" required style="width: 400px; margin-left:50px;">

        <el-form-item :label="$t('system.menu.name')" prop="name">
          <el-input v-model="menu.name" placeholder="Please input menu name" />
        </el-form-item>

        <el-form-item :label="$t('system.menu.parentName')" prop="parentId">
          <el-input v-model="menu.parentName" suffix-icon="el-icon-view" readonly @focus="parentSelect()" />
        </el-form-item>
        <el-form-item :label="$t('system.menu.orderNum')">
          <el-input-number v-model="menu.orderNum" controls-position="right" :min="0" :max="100" placeholder="Please input orderNum" />
        </el-form-item>

        <el-form-item :label="$t('system.menu.remark')">
          <el-input v-model="menu.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="dialogFormVisible = false">
          {{ $t('system.cancel') }}
        </el-button>
        <!--        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">-->
        <el-button v-waves v-no-more-click type="primary" @click="submitForm()">
          {{ $t('system.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { parseTime, getTime } from '@/utils'
import waves from '@/directive/waves' // waves directive
import noMoreClick from '@/directive/noMoreClick' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getTree, getRoutes, getMenu, createMenu, deleteMenu, updateMenu } from '@/api/menu'
import i18n from '@/lang'

const treeMenuData = []

const remarkOptions = [
  { key: '0', display_name: '男' },
  { key: '1', display_name: '女' },
  { key: '2', display_name: '未知' }
]

const statusDescOptions = [
  { key: '0', display_name: '启用' },
  { key: '1', display_name: '禁用' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const remarkKeyValue = remarkOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const statusKeyValue = statusDescOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const defaultForm = {
  name: '', // 部门标题
  parentId: '', // 父部门
  parentName: '', // 父部门
  orderNum: '', // 部门排序
  level: 0, // 部门层级
  remark: '', // 部门备注
  menuId: undefined, // 部门ID
  createTime: 0,
  updateTime: 0
}

const defaultMenu = {
  menuId: undefined,
  name: '',
  parentId: '',
  parentName: '',
  orderNum: 0,
  level: 0,
  remark: '',
  createTime: 0,
  updateTime: 0
}

export default {
  name: 'MenuList',
  components: { Pagination },
  directives: { waves, noMoreClick },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'info',
        0: 'success'
      }
      return statusMap[status]
    },
    statusDescFilter(status) {
      return statusKeyValue[status]
    },
    remarkFilter(remark) {
      return remarkKeyValue[remark]
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value == null || value === '') {
        this.$message({
          message: this.$t('system.menu.' + rule.field) + '为必传项',
          type: 'error'
        })
        callback(new Error(this.$t('system.menu.' + rule.field) + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      dataForm: Object.assign({}, defaultForm),
      canSave: false,
      tableKey: 0,
      menuList: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        remark: undefined,
        sort: ''
      },
      treeMenuData,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogInnerVisible: false,
      statusDescOptions,
      remarkOptions,
      sortOptions: [{ label: this.$t('system.menu.createTimeAscending'), key: '+CreateTime' }, { label: this.$t('system.menu.createTimeDescending'), key: '-CreateTime' }],
      statusOptions: ['1', '0'],
      showReviewer: false,
      menu: Object.assign({}, defaultMenu),
      dialogFormVisible: false,
      menuTreeDefaultKeys: [],
      dialogStatus: '',
      showCreator: false,
      textMap: {
        update: this.$t('system.menu.updateMenu'),
        create: this.$t('system.menu.createMenu')
      },
      dialogPvVisible: false,
      rules: {
        parentId: [{ required: true, validator: validateRequire }],
        name: [{ required: true, validator: validateRequire }]
      },
      multipleSelection: [],
      downloadLoading: false
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getMenu()
    this.loadMenuTree()
  },
  methods: {
    async getRoutes() {
      const res = await getRoutes()
      this.serviceRoutes = res.data
      const routes = this.generateRoutes(res.data)
      this.routes = this.i18n(routes)
    },
    async getMenu() {
      this.listLoading = true
      getMenu(this.listQuery).then(response => {
        this.menuList = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    async loadMenuTree() {
      getTree().then(response => {
        this.treeMenuData = response.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getMenu()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    reverseSelect() {
      const temp = []
      this.menuList.forEach(item => {
        !this.multipleSelection.includes(item.menuId) && temp.push(item)
      })
      this.toggleSelection(temp)
    },
    parentSelect() {
      this.loadMenuTree()
      this.dialogInnerVisible = true
    },
    menuTreeCheckChange(data, checked, child) {
      if (checked === true) {
        this.menu.parentId = data.menuId
        this.menu.parentName = data.name
        this.$refs.menuTree.setCheckedKeys([data.menuId])
        this.dialogInnerVisible = false
      } else {
        if (this.menu.parentId === data.menuId) {
          this.menu.parentId = data.menuId
          this.menu.parentName = data.name
          this.$refs.menuTree.setCheckedKeys([data.menuId])
          this.dialogInnerVisible = false
        }
      }
    },
    menuTreeClick(data, checked, child) {
      this.menu.level = checked.level
      this.menu.parentId = data.menuId
      this.menu.parentName = data.name
      this.$refs.menuTree.setCheckedKeys([data.menuId])
      this.dialogInnerVisible = false
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'menuId') {
        this.sortByID(order)
      } else if (prop === 'createTime') {
        this.sortByCreateTime(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    sortByCreateTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+CreateTime'
      } else {
        this.listQuery.sort = '-CreateTime'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.menu = {
        menuId: undefined,
        name: '',
        parentId: '',
        parentName: '',
        deleteFlag: '0',
        level: 0,
        orderNum: 0,
        createTime: 0,
        updateTime: 0
      }
    },
    i18n(routes) {
      const app = routes.map(route => {
        route.title = i18n.t(`route.${route.title}`)
        if (route.children) {
          route.children = this.i18n(route.children)
        }
        return route
      })
      return app
    },
    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.menu.createTime = getTime('start')
      this.menu.parentName = '顶级'
      this.menu.parentId = '0'
      this.menu.level = 0
      this.menuTreeDefaultKeys = []
      this.menuTreeDefaultKeys.push(0)
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(scope) {
      this.menu = Object.assign({}, scope.row) // copy obj
      this.menu.updateTime = getTime('start')
      this.menu.parentId = scope.row.parentId
      this.menu.parentName = scope.row.parentName
      this.dialogStatus = 'update'
      this.menu.level = scope.row.level
      this.menuTreeDefaultKeys = []
      this.menuTreeDefaultKeys.push(this.menu.parentId)
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm(this.$t('system.confirmRemove', { msg: this.$t('system.menu.menu') }), this.$t('system.warning'), {
        confirmButtonText: this.$t('system.confirm'),
        cancelButtonText: this.$t('system.cancel'),
        type: 'warning'
      })
        .then(async() => {
          await deleteMenu(row.menuId)
          this.menuList.splice($index, 1)
          this.$message({
            type: 'success',
            message: this.$t('system.deleteSuccessfully', { msg: this.$t('system.menu.menu') })
          })
          this.$notify({
            title: this.$t('system.success'),
            message: this.$t('system.deleteSuccessfully', { msg: this.$t('system.menu.menu') }),
            type: 'success',
            duration: 2000
          })
        })
        .catch(err => {
          if (err === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          } else {
            console.error(err)
          }
        })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = Object.assign([], Object.keys(defaultMenu))
        const filterVal = Object.assign([], Object.keys(defaultMenu))
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.$t('system.menu.menu') + '-' + this.$t('system.list') + getTime('start')
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.menuList.map(v => filterVal.map(j => {
        if (j === 'createTime') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    submitForm() {
      this.canSave = true
      console.log(this.dataForm)
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (this.canSave) {
            this.confirmMenu()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async confirmMenu() {
      const isEdit = this.dialogStatus === 'update'
      if (isEdit) {
        await updateMenu(this.menu)
        for (let index = 0; index < this.menuList.length; index++) {
          if (this.menuList[index].menuId === this.menu.menuId) {
            this.menuList.splice(index, 1, Object.assign({}, this.menu))
            this.dialogFormVisible = false
            break
          }
        }
      } else {
        const { data } = await createMenu(this.menu)
        this.menu.menuId = data.menuId
        this.menuList.push(this.menu)
        this.dialogFormVisible = false
      }

      const { parentName, remark, name } = this.menu
      this.dialogVisible = false
      this.canSave = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
              <div>Name: ${name}</div>
              <div>Parent Name: ${parentName}</div>
              <div>remark: ${remark}</div>
            `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
